#include <iostream>
#include <vector>
#include <thread>
#include <atomic>
#include <jsoncpp/json/json.h>
#include <opencv2/opencv.hpp>
#include <csignal>

// RTSP相机配置结构体
struct CameraConfig {
    std::string ip;
    std::string rtsp_url;
    std::string rtmp_url;
};

// 全局停止标志
std::atomic<bool> stop_flag(false);

// 信号处理函数
void signal_handler(int signum) {
    stop_flag = true;
}

// 单个相机推流线程
void stream_camera(const CameraConfig& cam) {
    // 创建RTSP捕获对象
    cv::VideoCapture cap(cam.rtsp_url, cv::CAP_FFMPEG);
    if (!cap.isOpened()) {
        std::cerr << "Error opening camera: " << cam.ip << std::endl;
        return;
    }

    // 设置分辨率 (1080p)
    cap.set(cv::CAP_PROP_FRAME_WIDTH, 1280);
    cap.set(cv::CAP_PROP_FRAME_HEIGHT, 720);
    cap.set(cv::CAP_PROP_FPS, 24);

    // FFmpeg推流管道配置
    std::string ffmpeg_cmd = "ffmpeg -rtsp_transport tcp -use_wallclock_as_timestamps 1 -fflags nobuffer  -i \"" + cam.rtsp_url + "\" -an -c:v copy -c:a aac -f flv \"" + cam.rtmp_url + "\"";
    
    // 打开FFmpeg管道
    FILE* ffmpeg_pipe = popen(ffmpeg_cmd.c_str(), "w");
    if (!ffmpeg_pipe) {
        std::cerr << "Error opening FFmpeg pipe for: " << cam.ip << std::endl;
        return;
    }

    std::cout << "Started streaming from " << cam.ip << " to " << cam.rtmp_url << std::endl;

    // 主处理循环
    cv::Mat frame;
    while (!stop_flag) {
        if (!cap.read(frame)) {
            std::cerr << "Frame read error from: " << cam.ip << std::endl;
            break;
        }

        if (!frame.empty()) {
            fwrite(frame.data, 1, frame.total() * frame.elemSize(), ffmpeg_pipe);
        }
    }

    // 清理资源
    pclose(ffmpeg_pipe);
    cap.release();
    std::cout << "Stopped streaming from " << cam.ip << std::endl;
}

int main(int argc, char* argv[]) {
    if (argc != 2) {
        std::cerr << "Usage: " << argv[0] << " <config.json>" << std::endl;
        return 1;
    }

    // 注册信号处理
    signal(SIGINT, signal_handler);
    signal(SIGTERM, signal_handler);

    // 加载配置文件
    Json::Value config;
    std::ifstream config_file(argv[1]);
    if (!config_file.is_open()) {
        std::cerr << "Error opening config file" << std::endl;
        return 1;
    }
    config_file >> config;

    // 解析相机配置
    std::vector<CameraConfig> cameras;
    for (const auto& cam_cfg : config["cameras"]) {
        std::string ip = cam_cfg["ip"].asString();
        cameras.push_back({
            ip,
            "rtsp://" + ip + ":554/0",  // 主码流
            cam_cfg["rtmp_url"].asString()
        });
    }

    // 创建推流线程
    std::vector<std::thread> threads;
    for (const auto& cam : cameras) {
        threads.emplace_back(stream_camera, cam);
    }

    // 等待所有线程结束
    for (auto& t : threads) {
        t.join();
    }

    return 0;
}